/**
 * Project hdmap
 * @author shengjialiang
 * @version v1.0
 */


#include "map_helper/FileAccessor.h"
#include <io.h>
#include <direct.h>

/**
 * FileAccessor implementation
 */

namespace Helper
{
    CFileAccessor::CFileAccessor()
    {

    }

    CFileAccessor::~CFileAccessor()
    {

    }

    bool CFileAccessor::exist(const std::string& in_path)
    {
        bool r = false;
        r = (_access(in_path.c_str(), 0) != -1);
        return r;
    }

    std::string CFileAccessor::readFile(const std::string& in_path)
    {
        std::string content = "";
        if ((_access(in_path.c_str(), 0)) != -1)
        {
            FILE* file = nullptr;
            fopen_s(&file, in_path.c_str(), "r+");
            if (file)
            {
                int length = 0;
                fseek(file, 0, SEEK_END);
                length = ftell(file);
                fseek(file, 0, SEEK_SET);
                char *jsonfile = new char[length + 1];
                fread(jsonfile, 1, length, file);
                jsonfile[length] = '\0';
                fclose(file);
                content = jsonfile;
                delete[]jsonfile;
            }
        }
        return content;
    }

    bool CFileAccessor::writeFileEx(std::string& data, const std::string& in_path)
    {
        bool r = false;
        FILE* file = nullptr;
        fopen_s(&file, in_path.c_str(), "a+ ");
        if (file)
        {
            fputs(data.c_str(), file);
            fclose(file);
            r = true;
        }
        return r;
    }

    bool CFileAccessor::writeFile(std::string& data, const std::string& in_path)
    {
        bool r = false;
        FILE* file = nullptr;
        fopen_s(&file, in_path.c_str(), "wb");
        if (file)
        {
            fputs(data.c_str(), file);
            fclose(file);
            r = true;
        }
        return r;
    }

    bool CFileAccessor::getOrCreateDir(const std::string& cacheDir)
    {
        bool r = false;
        if (_access(cacheDir.c_str(), 6) == -1)
        {
            _mkdir(cacheDir.c_str());
            r = true;
        }
        return r;
    }

}